﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Configuration;

namespace DiBang.Common
{
    public class SerialPortProcess
    {
        /// <summary>
        /// 串口传输的数据解码
        /// </summary>
        /// <param name="buffer">串口的buffer数据</param>
        /// <returns>解码后的重量,double类型</returns>
        public static double GetBuffer(byte[] buffer)
        {
            double dResult = -1;

            if (buffer.Length < 12)
            {
                return dResult;
            }

            try
            {
                for (int i = 0; i < buffer.Length; i++)
                {
                    if ((buffer[i] == 0x02 && buffer[i + 1] == 0x2B)
                        || (buffer[i] == 0x02 && buffer[i + 1] == 0x2D))
                    {
                        //符合规则的进行读取数据,不符合规则的直接丢弃

                        //取符号
                        byte Op = buffer[i + 1];
                        //这里取到字符串2-8字节数值内容                          
                        string data = System.Text.Encoding.ASCII.GetString(buffer, i + 2, i + 7);
                        //小数点位值             
                        int pointAt = int.Parse(data.Substring(data.Length - 1, 1));
                        //去掉小数位             
                        data = data.Substring(0, data.Length - 1);
                        //去掉左边的0             
                        data = data.TrimStart('0');
                        int inData = 0;
                        int.TryParse(data, out inData);
                        //计算小数 
                        double db = inData * Math.Pow(0.1, pointAt);
                        //正负返回          
                        return Op == 0x2D ? 0 - db : db;
                    }
                }
            }
            catch
            {
                return dResult;
            }

            return dResult;
        }
    }
}
